pagetutor.com - HTML tutorials for the rest of us

Javascript Tutor - Lesson 12

Another "built in" array is the options array in a drop down list. Consider the following list...

It's HTML is as follows:

<FORM NAME="form02">
<SELECT NAME="bradykids">
<OPTION VALUE="greg"  >Greg
<OPTION VALUE="marsha">Marsha
<OPTION VALUE="peter" >Peter
<OPTION VALUE="jan"   >Jan
<OPTION VALUE="bobby" >Bobby
<OPTION VALUE="cindy" >Cindy
</SELECT>
</FORM>

Notice the list has a name and each option has a value.

Look at the following script...

<HTML>
<HEAD>
<TITLE></TITLE>

<SCRIPT language="Javascript"><!--

function GoBrady()
{
   brady = window.document.form02.bradykids.selectedIndex;
   alert(brady);
}

//--></SCRIPT>

</HEAD>
<BODY>

<FORM NAME="form02">
<SELECT NAME="bradykids" onChange="GoBrady()">
<OPTION VALUE="greg"  >Greg
<OPTION VALUE="marsha">Marsha
<OPTION VALUE="peter" >Peter
<OPTION VALUE="jan"   >Jan
<OPTION VALUE="bobby" >Bobby
<OPTION VALUE="cindy" >Cindy
</SELECT>
</FORM>

</BODY>
</HTML>

Try it.

It uses the event handler onChange. When the state of the drop down list changes it invokes the function GoBrady(). This function throws up an alert box displaying the selectedIndex property of the options array. Fiddle with it until you understand what's going on.

Alrighty, we can easily get the index of the selected Brady. But, how can we get the value? Well, where the selectedIndex is a property of the array, the values are properties of the individual options. Does that make sense?

Remember when we were looking at image arrays and we said that the first image in the array is images[0], the second is images[1] and so forth? Well, the options array is similar. We named our array bradykids, so the first option is bradykids[0], the second is bradykids[1], the third is bradykids[2], etc. In the last script we grabbed the selectedIndex and stored it in the variable brady. So, we could get properties of individual options with bradykids[brady]. Do I still have you or are you hopelessly confused? Have a look at this modified version of the last script...

<HTML>
<HEAD>
<TITLE></TITLE>

<SCRIPT language="Javascript"><!--

function GoBrady()
{
   brady = window.document.form02.bradykids.selectedIndex
   alert(window.document.form02.bradykids[brady].value);
}

//--></SCRIPT>

</HEAD>
<BODY>

<FORM NAME="form02">
<SELECT NAME="bradykids" onChange="GoBrady()">
<OPTION VALUE="greg"  >Greg
<OPTION VALUE="marsha">Marsha
<OPTION VALUE="peter" >Peter
<OPTION VALUE="jan"   >Jan
<OPTION VALUE="bobby" >Bobby
<OPTION VALUE="cindy" >Cindy
</SELECT>
</FORM>

</BODY>
</HTML>

Try it.

Keep studying it until you understand it.

<< BACK         NEXT >>
pagetutor.com



Invest in the future - Hug your kid today.